import dataclasses
import matplotlib.axes
import matplotlib.pyplot
import numpy
import pathlib
from typing import Any, Type, Optional, Union, Callable, Sequence  # , Dict, List, Set, Tuple
import vnpy.tools.database_cta
import vnpy.trader.utility
from vnpy.trader.constant import Direction, Exchange, Interval, Offset, Status, Product, OptionType, OrderType


@dataclasses.dataclass
class DrawData:
    """"""
    title: str = None
    xpoints: numpy.ndarray = None
    ypoints: numpy.ndarray = None


@dataclasses.dataclass(frozen=True)
class KeyData:
    """"""
    strategy_name: str = ""  # 交易策略
    interval: Interval = None  # K线周期
    exchange: Exchange = None  # 交易所(self.exchange.value)
    symbol: str = ""  # 代码
    setting_day_trading: int = None
    # setting_interval
    # setting_line_window


def load_data(sqlite_filepath: Union[str, pathlib.Path, None]) -> list[DrawData]:
    """"""
    database = vnpy.tools.database_cta.get_database()
    database.reinitialize(sqlite_filepath=sqlite_filepath)

    cta_statistics_data_s: list[vnpy.tools.database_cta.CtaStatisticsData] = database.load_cta_statistics_data()

    mapping: dict[KeyData, list[vnpy.tools.database_cta.CtaStatisticsData]] = {}
    for cta_statistics_data in cta_statistics_data_s:
        assert cta_statistics_data.setting["interval"] == cta_statistics_data.interval.value

        key_data = KeyData(
            strategy_name=cta_statistics_data.strategy_name,
            interval=cta_statistics_data.interval,
            exchange=cta_statistics_data.exchange,
            symbol=cta_statistics_data.symbol,
            setting_day_trading=cta_statistics_data.setting["day_trading"],
        )
        mapping.setdefault(key_data, [])
        mapping[key_data].append(cta_statistics_data)

    draw_data_s: list[DrawData] = []
    for key_data, cta_statistics_data_s in mapping.items():
        cta_statistics_data_s.sort(key=lambda _: _.setting["line_window"])

        draw_data = DrawData(
            title=f"{key_data.exchange.value}.{key_data.symbol}_{key_data.setting_day_trading}",
            xpoints=numpy.array([_.setting["line_window"] for _ in cta_statistics_data_s]),
            ypoints=numpy.array([_.result["total_return"] for _ in cta_statistics_data_s]),
        )
        draw_data_s.append(draw_data)

    draw_data_s.sort(key=lambda _: _.title)

    return draw_data_s


def show_data(draw_data_s: list[DrawData]):
    """"""
    print("count:", len(draw_data_s))

    fig, axes = matplotlib.pyplot.subplots(nrows=11, ncols=14)
    fig.subplots_adjust(left=0.02, right=0.995, top=0.98, bottom=0.02)
    fig.canvas.manager.window.showMaximized()

    for idx, draw_data in enumerate(draw_data_s):
        row: int = idx // len(axes[0])
        col: int = idx % len(axes[0])

        ax: matplotlib.axes.Axes = axes[row][col]
        ax.set_title(draw_data.title)
        ax.set_xticks([])  # 取消x轴刻度
        ax.plot(draw_data.xpoints, draw_data.ypoints)

    matplotlib.pyplot.show()


if __name__ == "__main__":
    sqlite_filepath: pathlib.Path = vnpy.trader.utility.get_file_path("database_cta_cont.db")
    draw_data_s: list[DrawData] = load_data(sqlite_filepath=sqlite_filepath)
    show_data(draw_data_s=draw_data_s)
